package com.sunseen.intelligencebus;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import com.sunseen.intelligencebus.home.BusMsgGotEvent;
import com.sunseen.intelligencebus.home.SendMsgEvent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

import static androidx.core.app.NotificationCompat.PRIORITY_MIN;

public class BtMsgService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    private final String TAG = BtMsgService.class.getSimpleName();

    private BluetoothAdapter mBluetoothAdapter;

    private ArrayList<BluetoothDevice> bluetoothDeviceList = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        String channelId = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId = createNotificationChannel("my_service", "Bluetooth Background Service");
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
        Notification notification = builder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_intelligence_bus_launcher)
                .setContentTitle("蓝牙通讯")
                .setContentText("正在运行")
                .setPriority(PRIORITY_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(110, notification);
        initReceiver();
        initReadThread();
        return super.onStartCommand(intent, flags, startId);
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(String channelIdStr, String channerName) {
        NotificationChannel chan = new NotificationChannel(channelIdStr, channerName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.GREEN);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(chan);
        return channelIdStr;
    }

    @Override
    public void onDestroy() {
        stopForeground(true); 
        super.onDestroy();
        if (mBtChangeReceiver != null) {
            unregisterReceiver(mBtChangeReceiver);
        }
    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        mBtChangeReceiver = new BtChangeReceiver();
        getApplicationContext().registerReceiver(mBtChangeReceiver, filter);
    }

    private BtChangeReceiver mBtChangeReceiver;

    private class BtChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("test", "action = " + intent.getAction());
            switch (intent.getAction()) {
                case BluetoothDevice.ACTION_ACL_CONNECTED: {
                    Log.e("bt", "ACTION_ACL_CONNECTED");
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    if (readThread == null) {
                        readThread = new ReadThread(device);
                        Log.e("bt", "in ACTION_ACL_CONNECTED readThread started");
                        readThread.start();
                    }
                }
                break;
                case BluetoothDevice.ACTION_ACL_DISCONNECTED: {
                    if (readThread != null) {
                        readThread.stopRun();
                        readThread = null;
                    }
                }
                break;
            }
        }
    }

    private void initReadThread() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(), "该设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }

        Set<BluetoothDevice> btDevicesSet = mBluetoothAdapter.getBondedDevices();
        Log.e("bt", "bondedDevices.size = " + btDevicesSet.size());
        if (btDevicesSet.size() > 0) {
            bluetoothDeviceList.addAll(btDevicesSet);
            readThread = new ReadThread(bluetoothDeviceList.get(0));
            readThread.start();
            Log.e("bt", "readThreadStarted");
        }
    }

    private ReadThread readThread = null;

    private class ReadThread extends Thread {

        private BluetoothDevice goalDevice;
        private InputStream mInputStream;
        private boolean runFlag = true;

        ReadThread(BluetoothDevice bluetoothdevice) {
            goalDevice = bluetoothdevice;
        }

        @Override
        public void run() {
            try {
                Method clientMethod = goalDevice.getClass()
                        .getMethod("createRfcommSocket", new Class[]{int.class});
                BluetoothSocket remoteSocket = (BluetoothSocket) clientMethod.invoke(goalDevice, 1);
                Log.e(TAG, "before connect");
                remoteSocket.connect();
                Log.e(TAG, "after connect");
                mInputStream = remoteSocket.getInputStream();   //建立输入流读取数据
                byte[] buffer = new byte[1024];
                int length;
                while (runFlag) {
                    try {
                        if ((length = mInputStream.read(buffer)) > 0) {
                            Log.e(TAG, "in read thread ");
                            byte[] bytes = new byte[length];
                            for (int i = 0; i < length; i++) {
                                Log.e(TAG, "byte = " + buffer[i]);
                                bytes[i] = buffer[i];
                            }
                            EventBus.getDefault().post(new BusMsgGotEvent(bytes));
                        }
                    } catch (Exception e) {
                        Log.e(TAG, e.toString());
                        break;
                    }
                }
                if (remoteSocket != null) {
                    remoteSocket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void stopRun() {
            runFlag = false;
            if (mInputStream != null) {
                try {
                    mInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, "in ReadThread stopRun() IOException");
                }
            }
        }
    }
}
